package com.sanjiahantang.youjiaclient.module.store.preseneters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.uilibrary.views.CircleImageView;
import com.sanjiahantang.uilibrary.views.MyGridView;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseMvpPresenter;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.base.CallBack;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.StaticValue;
import com.sanjiahantang.youjiaclient.module.cases.views.impl.DesignerDetailActivity;
import com.sanjiahantang.youjiaclient.module.store.beans.StoreDetailBean;
import com.sanjiahantang.youjiaclient.module.store.models.IStoreModel;
import com.sanjiahantang.youjiaclient.module.store.models.impl.StoreModel;
import com.sanjiahantang.youjiaclient.module.store.views.StoreDetailView;
import com.sanjiahantang.youjiaclient.module.store.views.impl.DesignerListActivity;
import com.sanjiahantang.youjiaclient.utils.FileUtils;
import com.squareup.picasso.Picasso;

import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.squareup.picasso.MemoryPolicy.NO_CACHE;
import static com.squareup.picasso.MemoryPolicy.NO_STORE;

/**
 * Created by yan on 2018/1/3.
 */

public class StoreDetailPresenter extends BaseMvpPresenter<StoreDetailView> {

    private IStoreModel storeModel;
    private QuickAdapter evaluationAdapter;
    private GalleryAdapter designerAdapter;
    private List<StoreDetailBean.DesignerDetial> designerBeens;
    private StoreDetailView.OnListLoadListener onListLoadListener;

    public StoreDetailPresenter() {
        storeModel = new StoreModel();
        designerBeens = new ArrayList<>();
    }

    //初始化配置，添加适配器
    public void initContainers(Context context, StoreDetailView.OnListLoadListener onListLoadListener) {
        this.onListLoadListener = onListLoadListener;
        evaluationAdapter = new QuickAdapter<StoreDetailBean.Appraise>(context, R.layout.item_eva_store_unlogin) {
            @Override
            protected void convert(BaseAdapterHelper helper, StoreDetailBean.Appraise item) {
                if (item.getPhone() != null){
                    ((TextView) helper.getView(R.id.txtPhone)).setText(item.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
                }
                ((TextView) helper.getView(R.id.txtCreateTime)).setText(item.getCreateTime());
                ((TextView) helper.getView(R.id.txtContent)).setText(item.getPlace() + "");
                RatingBar ratingBar = helper.getView(R.id.ratingBar);
                try {
                    ratingBar.setRating(item.getUserNumber());
                    ratingBar.setIsIndicator(true);
                } catch (NumberFormatException e) {
                    Log.e("rating", e.getMessage());
                }
                MyGridView myGridView = helper.getView(R.id.gvImageList);
                myGridView.setAdapter(new QuickAdapter<StoreDetailBean.Icon>(context, R.layout.item_image, item.getImgList()) {
                    @Override
                    protected void convert(com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper helper, final StoreDetailBean.Icon item) {
                        ImageView iv = helper.getView(R.id.image);
                        Picasso.with(context).load(FileUtils.rePath(item.getUrl())).memoryPolicy(NO_CACHE, NO_STORE).placeholder(R.drawable.i_rect_bg).into(iv);
                        iv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Utils.showPicDialog((Activity) context,FileUtils.rePath(item.getUrl()),R.drawable.i_rect_bg);
                            }
                        });

                    }
                });

            }
        };


        CommonNavigator navigator = new CommonNavigator(context);
        designerAdapter = new GalleryAdapter();
        navigator.setAdapter(designerAdapter);

        onListLoadListener.initContainers(navigator, evaluationAdapter);

    }

    /**
     * 请求详情界面数据
     *
     * @param context
     * @param id
     */
    public void loadData(Context context, String id, final BaseView.OnLoadListener listener) {
        Map<String, String> param = new HashMap<>();
        if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
            param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        }
        param.put(KEY_ROLEID, id);

        mView.showProgress();
        storeModel.loadStoreDetail(context, param, new CallBack<StoreDetailBean>() {
            @Override
            public void onSuccess(StoreDetailBean response, Context context, Object tag) {
                hideProgress();
                if (response.getCode() == StaticValue.RESPONSE_CODE_SUC) {
                    listener.onLoad(response.getData());
                    evaluationAdapter.clear();
                    evaluationAdapter.addAll(response.getData().getAppraiseList());

                    designerAdapter.addAll(response.getData().getDesignList());
                } else if (response.getCode() == StaticValue.RESPONSE_CODE_FAIL) {
                    ((Activity) context).finish();
                }
            }

            @Override
            public void onFailure(String message) {
                hideProgress();
            }
        });
    }

    /**
     * 设计师预览适配器
     */
    private class GalleryAdapter extends CommonNavigatorAdapter {

        private List<StoreDetailBean.DesignerDetial> designerDetial;

        public void addAll(List<StoreDetailBean.DesignerDetial> list) {
            if (designerDetial == null) {
                designerDetial = new ArrayList<>();
            }
            if (list.size() > 10) {
                List<StoreDetailBean.DesignerDetial> designerDetial = new ArrayList<>();
                for (int i = 0; i < 10; i++) {
                    designerDetial.add(list.get(i));
                }
                list.clear();
                list.addAll(designerDetial);
            }
            designerDetial.addAll(list);
            notifyDataSetChanged();
        }


        @Override
        public int getCount() {
            return designerDetial == null ? 0 : designerDetial.size();
        }

        @Override
        public IPagerTitleView getTitleView(final Context context, int i) {
            CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);
            final View contentView = LayoutInflater.from(context).inflate(R.layout.item_store_detail_gridview, null);
            commonPagerTitleView.setContentView(contentView);
            final StoreDetailBean.DesignerDetial item = designerDetial.get(i);
            TextView year = (TextView) contentView.findViewById(R.id.item_store_detail_year_tv);
            TextView username = (TextView) contentView.findViewById(R.id.item_store_detail_designername_tv);
            CircleImageView circleImageView = (CircleImageView) contentView.findViewById(R.id.item_store_detail_designerhead_civ);
            year.setText("签约" + ((item.getToDay() / 365) + 1) + "年");
            username.setText(item.getUserName());
            Picasso.with(context).load(FileUtils.rePath(item.getUrl())).placeholder(R.drawable.i_head_default).into(circleImageView);
            commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    context.startActivity(new Intent(context, DesignerDetailActivity.class)
                            .putExtra(KEY_PHONE, item.getRoleId()));
                }
            });
            return commonPagerTitleView;
        }

        @Override
        public IPagerIndicator getIndicator(Context context) {
            return null;
        }
    }

    /**
     * 动态添加ImageView
     *
     * @param context
     * @param linearLayout
     * @param icons
     */
    public void addIconsView(Context context, LinearLayout linearLayout, List<StoreDetailBean.Icon> icons) {
        linearLayout.removeAllViews();
        for (int i = 0; i < icons.size(); i++) {
            ImageView imageView = new ImageView(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.gravity = Gravity.CENTER_VERTICAL;
            imageView.setLayoutParams(params);
            imageView.setPadding(10,0,10,0);
            Picasso.with(context).load(FileUtils.rePath(icons.get(i).getUrl())).into(imageView);
            linearLayout.addView(imageView);
        }

    }


    private void hideProgress() {
        if (mView != null) {
            mView.hideProgress();
        }
    }
}
